package com.seo.controller.keyWord;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.github.pagehelper.PageInfo;
import com.seo.function.PageTool;
import com.seo.pojo.InputBody;
import com.seo.pojo.ReturnBody;
import com.seo.service.keyword.sdk.KeywordService;
import com.seo.service.user.sdk.UserService;
import com.seo.utils.ClientConst;
import com.seo.utils.Jurisdiction;

import lombok.extern.slf4j.Slf4j;

/**
 * @ClassName: KeyWordController
 * @author rtc
 * @version 2018.07.28 12:20
 */
@Slf4j
@Controller
@RequestMapping(value = "keyWord/")
public class KeyWordController {

	@Resource(name = "keywordService")
	private KeywordService keywordService;

	@Resource(name = "userService")
	private UserService userService;

	@Autowired
	private PageTool pageTool;

	/**
	 * 获取关键词报价
	 * 
	 * @param keyWord
	 *            关键词
	 * @param type
	 *            用户类型
	 * @return Map<String,Object>
	 */
	@RequestMapping(value = "proxy/offer")
	public ModelAndView proxyListOffer(@RequestParam Map<String, Object> param) throws Exception {
		log.info("获取关键词报价开始---param={}", param);
		ModelAndView mv = new ModelAndView();
		List<Map<String, Object>> keyWordOffer = null;
		Integer userId = Jurisdiction.getT("id", Integer.class, ClientConst.SESSION_USER);
		if (!param.isEmpty()) {
			if (Jurisdiction.roleCode("proxy")) {
				param.put("type", "01");
			} else {
				param.put("type", "00");
			}
			param.put("userId", userId);
			keyWordOffer = keywordService.getKeyWordOffer(param);
		}
		mv.addObject("keyWord", param.get("keyWord"));
		mv.addObject("keyWordOffer", keyWordOffer);
		mv.setViewName("keyWord/keyWord_proxy_offer");
		log.info("获取关键词报价结束");
		return mv;
	}
	
	/**
	 * 获取关键词报价
	 * 
	 * @param keyWord
	 *            关键词
	 * @param type
	 *            用户类型
	 * @return Map<String,Object>
	 */
	@RequestMapping(value = "/offer")
	public ModelAndView listOffer(@RequestParam Map<String, Object> param) throws Exception {
		log.info("获取关键词报价开始---param={}", param);
		ModelAndView mv = new ModelAndView();
		List<Map<String, Object>> keyWordOffer = null;
		Integer userId = Jurisdiction.getT("id", Integer.class, ClientConst.SESSION_USER);
		if (!param.isEmpty()) {
			Map<String, Object> userById = userService.getUserById(userId);
			if (userById != null) {
				String price1 = userById.get("price1") + "";
				String price2 = userById.get("price2") + "";
				if (!StringUtils.isEmpty(price1) && !"0.0000".equals(price1) && !StringUtils.isEmpty(price2)
						&& !"0.0000".equals(price2)) {
					param.put("price1", price1);
					param.put("price2", price2);
					keyWordOffer = keywordService.getKeyWordOffer1(param);
					mv.addObject("keyWord", param.get("keyWord"));
					mv.addObject("keyWordOffer", keyWordOffer);
					mv.setViewName("keyWord/keyWord_offer");
					return mv;
				}
			}
			if (Jurisdiction.roleCode("proxy")) {
				param.put("type", "01");
			} else {
				param.put("type", "00");
			}
			param.put("userId", userId);
			keyWordOffer = keywordService.getKeyWordOffer(param);
		}
		mv.addObject("keyWord", param.get("keyWord"));
		mv.addObject("keyWordOffer", keyWordOffer);
		mv.setViewName("keyWord/keyWord_offer");
		log.info("获取关键词报价结束");
		return mv;
	}

	/**
	 * 跳转关键词新增
	 * 
	 * @param param
	 *            param
	 * @return ModelAndView
	 * @author rtc
	 * @version 2018.07.28 12:20
	 */
	@RequestMapping(value = "/toKeyWordAdd")
	public ModelAndView toKeyWordAdd() throws Exception {
		log.info("【跳转关键词新增】---【开始】---");
		ModelAndView mv = new ModelAndView();
		List<Map<String, Object>> engine = keywordService.getEngineList();
		mv.addObject("engine", engine);
		if (Jurisdiction.roleCode("proxy")) {
			mv.addObject("proxy", "01");
		} else {
			mv.addObject("proxy", "02");
		}
		mv.setViewName("keyWord/keyWord_add");
		log.info("【跳转关键词新增】---【结束】---");
		return mv;
	}

	/**
	 * 关键词新增
	 * 
	 * @param param
	 *            param
	 * @return String
	 * @author rtc
	 * @version 2018.07.28 12:20
	 */
	@RequestMapping(value = "/add")
	@ResponseBody
	public ReturnBody add(@RequestParam Map<String, Object> param) throws Exception {
		log.info("【关键词新增】---【开始】---");
		ReturnBody rb = ReturnBody.init();
		Map<String, Object> user = Jurisdiction.getUser(ClientConst.SESSION_USER);
		try {
			if (user == null || user.isEmpty()) {
				return rb.error("用户不存在");
			}
			if (param == null || param.isEmpty()) {
				return rb.error("参数不能为空");
			}
			if (!param.containsKey("uploadType")) {
				return rb.error("请选择上传方式");
			}
			Map<String, Object> userById = userService.getUserById(Integer.parseInt(user.get("id") + ""));
			BigDecimal balance = new BigDecimal(userById.get("balance") + "");
			BigDecimal balances = new BigDecimal("500");
			if (balance.compareTo(balances) < 0) {
				rb.error("余额过低，请充值！");
				return rb;
			}
			String uploadType = (String) param.get("uploadType");
			param.put("createId", user.get("id"));
			param.put("user", user);
			if (!Jurisdiction.roleCode("proxy")) {
				rb.run(keywordService.saveKeyWord(param, "02", uploadType));
			} else {
				param.put("userId", user.get("id"));
				rb.run(keywordService.saveKeyWordProxy(param, uploadType));
			}
			log.info("【关键词新增】---【结束】---");
			return rb;
		} catch (Exception e) {
			log.error("添加关键词异常[{}]", e);
			return rb.error();
		}

	}

	/**
	 * 关键词指数列表
	 * 
	 * @return ModelAndView
	 * @author rtc
	 * @version 2018.07.28 12:20
	 */
	@RequestMapping(value = "/indexList")
	public ModelAndView indexList() throws Exception {
		log.info("【关键词指数列表】---【开始】---");
		ModelAndView mv = new ModelAndView();
		Integer userId = Jurisdiction.getT("id", Integer.class, ClientConst.SESSION_USER);
		List<Map<String, Object>> indexList = keywordService.getKeyWordIndexProxy(userId);
		mv.addObject("indexList", indexList);
		mv.setViewName("keyWord/keyWord_index_list");
		log.info("【跳转关键词新增】---【结束】---");
		return mv;
	}

	/**
	 * 跳转编辑关键词指数页面
	 * 
	 * @return ModelAndView
	 * @author rtc
	 * @version 2018.07.28 12:20
	 */
	@RequestMapping(value = "/toEditIndex")
	public ModelAndView toEditIndex(@RequestParam Map<String, Object> param) throws Exception {
		ModelAndView mv = new ModelAndView();
		if (param == null || param.isEmpty()) {
			mv.addObject("msg", "访问失败");
			mv.setViewName("keyWord/keyWord_index_list");
			return mv;
		}
		Integer id = Integer.parseInt(param.get("proxyId") + "");
		Map<String, Object> index = keywordService.getProxyIndexById(id);
		mv.addObject("index", index);
		mv.addObject("msg", "updateIndex");
		mv.addObject("param", param);
		mv.setViewName("keyWord/keyWord_index_edit");
		return mv;
	}

	/**
	 * 修改关键词指数
	 * 
	 * @return String
	 * @author rtc
	 * @version 2018.07.28 12:20
	 */
	@RequestMapping(value = "/updateIndex")
	public String updateIndex(HttpServletRequest request) throws Exception {
		log.info("修改指数");
		InputBody body = InputBody.init();
		ReturnBody rb = ReturnBody.init();
		Integer userId = Jurisdiction.getT("id", Integer.class, ClientConst.SESSION_USER);
		if (userId == null) {
			request.setAttribute("result", rb.error("用户不存在").getResult());
			return "save_result";
		}
		String id = body.get("id", String.class);
		if (StringUtils.isEmpty(id)) {
			request.setAttribute("result", rb.error("参数有误").getResult());
			return "save_result";
		}
		String min_index = body.get("min_index", String.class);
		if (StringUtils.isEmpty(min_index)) {
			request.setAttribute("result", rb.error("最小指数不能为空").getResult());
			return "save_result";
		}
		String max_index = body.get("max_index", String.class);
		if (StringUtils.isEmpty(max_index)) {
			request.setAttribute("result", rb.error("最大指数不能为空").getResult());
			return "save_result";
		}
		String price_1 = body.get("price_1", String.class);
		if (StringUtils.isEmpty(price_1)) {
			request.setAttribute("result", rb.error("特殊词价格不能为空").getResult());
			return "save_result";
		}
		String price_2 = body.get("price_2", String.class);
		if (StringUtils.isEmpty(price_2)) {
			request.setAttribute("result", rb.error("正常词价格不能为空").getResult());
			return "save_result";
		}
		Map<String, Object> user = userService.getUserById(userId);
		if (user == null) {
			request.setAttribute("result", rb.error("用户不存在").getResult());
			return "save_result";
		}
		BigDecimal price1 = new BigDecimal(user.get("price1") + "");
		BigDecimal price2 = new BigDecimal(user.get("price2") + "");
		BigDecimal Pprice1 = new BigDecimal(price_1);
		BigDecimal Pprice2 = new BigDecimal(price_2);
		if (Pprice1.compareTo(price1) == -1 || Pprice2.compareTo(price2) == -1) {
			request.setAttribute("result", rb.error("关键词价格有误").getResult());
			return "save_result";
		}
		body.getParams().put("userId", userId);
		rb = keywordService.saveProxyIndex(body.getParams());
		request.setAttribute("result", rb.getResult());
		return "save_result";
	}

	/**
	 * 关健字分组列表
	 * 
	 * @param params
	 *            params
	 * @param request
	 *            request
	 * @return String
	 */
	@RequestMapping(value = "group/list")
	public String balanceList(@RequestParam Map<String, Object> params, HttpServletRequest request) throws Exception {
		log.info("关健字分组列表");
		Integer userId = Jurisdiction.getT("id", Integer.class, ClientConst.SESSION_USER);
		if (params == null || params.isEmpty()) {
			params = new HashMap<>();
		}
		params.put("userId", userId);
		PageInfo<?> page = pageTool.getAutoPage(keywordService::getKeywordGroupList, params);
		request.setAttribute("page", page);
		request.setAttribute("param", params);
		return "keyWord/group/keyWord_group_list";
	}

	@RequestMapping(value = "group/toAdd")
	public String toAdd(HttpServletRequest request) {
		request.setAttribute("msg", "save");
		return "keyWord/group/keyWord_group_edit";
	}

	@RequestMapping(value = "group/toUpdate")
	public String toUpdate(@RequestParam Map<String, Object> params, HttpServletRequest request) {
		List<Map<String, Object>> group = keywordService.getKeywordGroupList(params);
		if (group != null) {
			request.setAttribute("group", group.get(0));
		}
		request.setAttribute("msg", "updateGroup");
		return "keyWord/group/keyWord_group_edit";
	}

	@RequestMapping(value = "group/save")
	public String save(@RequestParam Map<String, Object> params, HttpServletRequest request) {
		ReturnBody rb = ReturnBody.init();
		try {
			Integer userId = Jurisdiction.getT("id", Integer.class, ClientConst.SESSION_USER);
			params.put("userId", userId);
			int num = keywordService.saveGroup(params);
			if (num == 0) {
				request.setAttribute("result", rb.error("操作失败").getResult());
				return "save_result";
			}
		} catch (Exception e) {
			e.printStackTrace();
			request.setAttribute("result", rb.error("网络繁忙").getResult());
		}
		request.setAttribute("result", rb.success().getResult());
		return "save_result";
	}

	@RequestMapping(value = "group/updateGroup")
	public String updateGroup(@RequestParam Map<String, Object> params, HttpServletRequest request) {
		ReturnBody rb = ReturnBody.init();
		try {
			Integer userId = Jurisdiction.getT("id", Integer.class, ClientConst.SESSION_USER);
			params.put("userId", userId);
			int num = keywordService.updateGroup(params);
			if (num == 0) {
				request.setAttribute("result", rb.error("操作失败").getResult());
				return "save_result";
			}
		} catch (Exception e) {
			e.printStackTrace();
			request.setAttribute("result", rb.error("网络繁忙").getResult());
		}
		request.setAttribute("result", rb.success().getResult());
		return "save_result";
	}

	@RequestMapping(value = "group/deleteGroup")
	@ResponseBody
	public String deleteGroup(Integer id, HttpServletRequest request) {
		int num = keywordService.getKeywordGroupNum(id);
		if (num > 0) {
			return "exist";
		}
		num = keywordService.deleteGroup(id);
		return num == 1 ? "success" : "error";
	}

}
